package com.siro.auth.utils;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * mp代码生成器
 * 执行main方法控制台输入模块表名回车自动生成对应项目目录中
 * 参考：https://www.jianshu.com/p/33b643bf001f
 *
 * @author starsea
 * @date 2022-11-09 09:25
 */
public class CodeGenerator {

    /**
     * 读取控制台内容
     * @param tip
     * @return
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + "：");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

    public static void main(String[] args) {
        //代码生成器
        AutoGenerator mpg = new AutoGenerator();

        //全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        //设置代码生成路径
        gc.setOutputDir(projectPath + "/src/main/java");
        //是否覆盖以前文件
        gc.setFileOverride(true);
        //是否打开生成目录
        gc.setOpen(false);
        //设置项目作者名称
        gc.setAuthor("starsea");
        //设置主键策略
        gc.setIdType(IdType.AUTO);
        //生成基本ResultMap
        gc.setBaseResultMap(true);
        //生成基本ColumnList
        gc.setBaseColumnList(true);
        //去掉服务默认前缀
        gc.setServiceName("%sService");
        //设置时间类型
        gc.setDateType(DateType.ONLY_DATE);
        //实体属性 swagger2注解
        //gc.setSwagger2(true);
        mpg.setGlobalConfig(gc);

        //数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/db_authority_manage?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("123456");
        mpg.setDataSource(dsc);

        //包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent("com.siro.mp");
        mpg.setPackageInfo(pc);

        //自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        //如果模板引擎是 freemarker
        String templatePath = "/templates/mapper.xml.ftl";
        //如果模板引擎是 velocity
        //String templatePath = "/templates/mapper.xml.vm";

        //自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        //自定义配置会优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath + "/src/main/resources/mapper" + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        //配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        //配置自定义输出模板，指定自定义模板路径，注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        //templateConfig.setController("templates/controllerGenerator.java");
        //templateConfig.setServiceImpl("templates/serviceImplGenerator.java");
        //templateConfig.setMapper("templates/mapperGenerator.java");
        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        //策略配置
        StrategyConfig strategy = new StrategyConfig();
        //数据库表映射到实体的命名策略:默命名:NamingStrategy.underline_to_camel认下划线转驼峰
        strategy.setNaming(NamingStrategy.underline_to_camel);
        //数据库表字段映射到实体的命名策略:默认下划线转驼峰命名:NamingStrategy.underline_to_camel
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        //自动lombok
        strategy.setEntityLombokModel(true);
        //默认继承BaseEntity类
        strategy.setSuperEntityClass("BaseEntity");
        //写于父类中的公共字段
        strategy.setSuperEntityColumns(new String[] {"create_by", "create_time", "update_by", "update_time" });

        //公共父类
        //sc.setSuperEntityClass("BaseController");
        //驼峰命名
        strategy.setRestControllerStyle(true);

        //设置逻辑删除
        //strategy.setLogicDeleteFieldName("deleted");
        //乐观锁
        //strategy.setVersionFieldName("version");
        //设置表名前缀
        //strategy.setTablePrefix("tbl_");

        strategy.setInclude(scanner("表名，多个英文逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());

        // 生成代码
        mpg.execute();
    }
}